import { defineStore } from 'pinia'
import { computed, reactive, ref } from 'vue'

export const useNotesStore = defineStore('notesStore', () => {
  const notes = ref([
    {
      id: 'id1',
      title: '日记',
      content: '到南京时，有友人约去游逛，勾留了一日；第二日上午便须渡江到浦口，下午上车北去。父亲因为事忙，本已说定不送我，叫旅馆里一个熟识的茶房陪我同去. 他再三嘱咐茶房，甚是仔细。但他终于不放心，怕茶房不妥帖；颇踌躇了一会。其实我那年已二十岁，北京已来往过两三次，是没有什么要紧的了。他踌躇了一会，终于决定还是自己送我去。我两三劝他不必去；他只说，“不要紧，他们去不好！”',
      datetime: '2023-04-14 22:27:36'
    },
    {
      id: 'id2',
      title: '学习任务',
      content: 'Vue3的setup语法糖使用, Sass的CSS语法, JS语法',
      datetime: '2023-04-16 11:27:36'
    },
    {
      id: 'id3',
      title: '工作',
      content: '日常开发维护, 编写开发文档',
      datetime: '2023-04-20 08:27:36'
    }
  ]);
  
  const addNote = (newNote, newTitle) => {
    const currentDate = new Date()
    // getTime返回的是数值, 须使用toString将其转化为字符串字面量
    const id = currentDate.getTime().toString()
    const datetime = currentDate.toLocaleString()
    const note = {
      id: id,
      title: newTitle,
      content: newNote,
      datetime: datetime
    }
    notes.value.unshift(note)
  };

  const deleteNode = (id) => {
    notes.value = notes.value.filter(note => {
      return note.id != id
    })
  };

  const getContentById = (id) => {
    return computed(() => notes.value.find(note => note.id === id))
  }

  const saveNote = (id, content, title) => {
    notes.value = notes.value.filter(item => item.id !== id)
    addNote(content, title)
    // const index = notes.value.findIndex(note => note.id === id)
  }


  const totalNotesCount = computed(() => notes.value.length)

  const totalCharactersCount = computed(() => {
    return notes.value.reduce((count, note) => {
      count += note.content.length
      return count
    }, 0)
  })

  return {
    notes,
    addNote,
    deleteNode,
    getContentById,
    saveNote,
    totalNotesCount,
    totalCharactersCount
  }
})

export const useCommentStore = defineStore('commentStore', () => {
  const comments = ref([
    {
      content: '好好学习天天向上',
      time: '2023/4/25 20:15:22'
    },
    {
      content: '学习了很多Vue3中组合式api的知识',
      time: '2023/4/24 10:23:55'
    },
    {
      content: '记事本开发的还不错',
      time: '2023/4/23 7:40:12'
    }
  ])

  const handleInputMessage = (inputValue) => {
    if (inputValue.value.trim() !== '') {
      const time = new Date().toLocaleString()
      const comment = {
        content: inputValue.value,
        time: time
      }
      comments.value.unshift(comment)
    }
  }

  const totalCommentCount = computed(() => comments.value.length)

  return {
    comments,
    handleInputMessage,
    totalCommentCount
  }
})